<?php

/*
本文件内所有函数以为fs开头
*/


/*
get_root得到绝对路径 根目录
return : e:/root
*/
//include_once("init.php");
function fs_get_root_a()
{
	return( DIR_ROOT_A );
	//return(	dirname(dirname(__FILE__))	);
}

/*
	物理路径
*/
function fs_get_root_p()
{
	return( DIR_ROOT_P );
}

//取值
function fs_get_value($v)
{	
	return isset($_REQUEST[$v])?$_REQUEST[$v]:'';
}

/*弹出信息 并且跳转		使用alert风格	在使用header 和 setcookie 时使用	意思就是在JQUERYUL弹出信息不能使用时使用*/
function fs_showmsg($msg , $url='')
{	
	if ($url==''){exit("<script type='text/javascript'>alert('".$msg."');history.back();</script>");}
	if ($url!=''){exit("<script type='text/javascript'>alert('".$msg."');location.href='".$url."';</script>");}
}

/*弹出信息 并且跳转		使用jquery ui风格	大多数能使用*/
function fs_showmsgui($msg , $url='')
{	
	if ($url==''){exit("<script type='text/javascript'>alert('".$msg."',historyback);</script>");}
	if ($url!=''){exit("<script type='text/javascript'>alert('".$msg."',locationhref,'".$url."');</script>");}
}
/*带有确定和取消的弹出信息 和跳转**/
function fs_jump($msg,$url){
        echo "<script type='text/javascript'>if(confirm('".$msg."')){history.back()}else{window.location.href='".$url."'}</script>";
}
function fs_jump2($msg,$url1,$url2){
        echo "<script type='text/javascript'>if(confirm('".$msg."')){window.location.href='".$url1."'}else{window.location.href='".$url2."'}</script>";
}
//check numer
function fs_checknumber($i)
{
	if (!fs_isNumber($i)){fs_showmsg('参数错误');}
	return $i;
}

//sha1加密
function fs_sha1($s)
{
	//return sha1($s).SHA;
	//return sha1($s.SHA);	//use this
	return md5($s);		//md5
}

//是否为合法的邮箱
function fs_isValidEmail($str){
	$reg="/[a-z0-9]([a-z0-9]*[-_\.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?/i";
	if(preg_match($reg,$str)){
		return true;
	}
	return false;
}

/*
-----------------------------------------------------------
函数名称：isNumber
简要描述：检查输入的是否为数字	
(^[0-9]+$)小数点也认为数字	
(^[0-9]*$)只认识整数
(^\+?[1-9][0-9]*$)非零的正整数
输入：string
输出：boolean
修改日志：------
-----------------------------------------------------------
*/
function fs_isNumber($val)
{
   if (ereg("^\+?[1-9][0-9]*$", $val)){return true;}
   return false;
}

/*
-----------------------------------------------------------
函数名称：isMobile
简要描述：检查输入的是否为手机号
输入：string
输出：boolean
修改日志：------
-----------------------------------------------------------
*/
function fs_isMobile($val)
{
   //该表达式可以验证那些不小心把连接符“-”写出“－”的或者下划线“_”的等等
   if (ereg("(^(\d{2,4}[-_－—]?)?\d{3,8}([-_－—]?\d{3,8})?([-_－—]?\d{1,7})?$)|(^0?1[35]\d{9}$)",$val))
    return true;
   return false;
}

/*-----------------------------------------------------------
函数名称：isChinese
简要描述：检查是否输入为汉字
输入：string
输出：boolean
修改日志：------
-----------------------------------------------------------
*/
function fs_isChinese($sInBuf)
{
   $iLen = strlen($sInBuf);
   for($i = 0; $i < $iLen; $i++)
   {
    if(ord($sInBuf{$i})>=0x80)
    {
     if( (ord($sInBuf{$i})>=0x81 && ord($sInBuf{$i})<=0xFE) && ((ord($sInBuf{$i+1})>=0x40 && ord($sInBuf{$i+1}) < 0x7E) || (ord($sInBuf{$i+1}) > 0x7E && ord($sInBuf{$i+1})<=0xFE)) )
     {
      if(ord($sInBuf{$i})>0xA0 && ord($sInBuf{$i})<0xAA)
      {
       //有中文标点
       return false;
      }
     }
     else
     {
      //有日文或其它文字
      return false;
     }
     $i++;
    }
    else
    {
     return false;
    }
   }
   return true;
}

/*
检查是否包含危险字符
可用于:
用户名
*/

function fs_checkstr()
{
	
}


/*
根据时间戳显示时间
0为显示 年月日
1为显示 年月日 时分秒
*/
function fs_get_formatetime($t,$s='1')
{
	if ($t=='' || is_null($t))	{	return '0000-00-00 00:00:00';	break;}
	switch ($s)
	{
		case	0	:	return date('Y-m-d',$t)		;	break;
		case	1	:	return date('Y-m-d H:i:s',$t);	break;
	}
}

/*
楼上函数名写错 :(--
根据时间戳显示时间
0为显示 年月日
1为显示 年月日 时分秒
*/
function fs_get_formattime($t,$s='1')
{
	if ($t=='' || is_null($t))	{	return '0000-00-00 00:00:00';	break;}
	switch ($s)
	{
		case	0	:	return date('Y-m-d',$t)		;	break;
		case	1	:	return date('Y-m-d H:i:s',$t);	break;
	}
}
function fs_get_star($i)
{
	switch ($i)
	{
		case 0:	return '普通教师'	;	break;
		case 1:	return '国家级名师'	;	break;
        case 2:	return '省级名师'	;	break;
        case 3:	return '校级名师'	;	break;
		default:return '未定义'	;	break;
	}
}

//根据状态ID返回用户状态
function fs_get_member_state($i)
{
	switch ($i)
	{
		case 0:	return '未激活'	;	break;
		case 1:	return '已激活'	;	break;
		default:return '未知'	;	break;
	}
}
//根据状态ID返回专家状态
function fs_get_expert_state($i)
{
	switch($i){
	case 0:  return '不显示'   ;    break;
	case 1:  return '显示'     ;    break;
	default: return '未知'     ;    break;
	}
}

//根据专业ID返回专业名称
function fs_get_major($i)
{
	if ( $i=='' || is_null($i) || !is_numeric($i))	{return '无专业';break;}
	
	global $db;
	$sql	=	"select name from ".TABLE_MAJOR." where major_id =$i ";
	$result =	$db -> query($sql);
	$row	=	$db->fetch_array($result);
	$str	=	$row['name'];
	return	$str;
}


//根据练习题ID返回练习题名称
function fs_get_testname($i)
{
	if ( $i=='' || is_null($i) || !is_numeric($i))	{return 'parameter error';break;}
	global $db;
	$sql	=	"select test_name from ".TABLE_TEST." where test_id=$i ";
	$result =	$db -> query($sql);
	$row	=	$db -> fetch_array($result);
	return	$row['test_name'];
}

/*
根据用户ID返回用户某个字段
参数:
$i	ID
$	字段名称
*/
function fs_get_memberinfo($i,$c)
{
	global $db;
	$sql	=	"select $c from ".TABLE_MEMBER." where id=$i";
	$result =	$db -> query($sql);
	$row	=	$db -> fetch_array($result);
	return	$row[$c];
}
//根据用户名获取用户ID
function getmemberid($username)
{
	global $db;
	$sql = "select * from ".TABLE_MEMBER." where username = '".$username."'";
	$result = $db -> query($sql);
	$row = $db -> fetch_array($result);
	return $row['id'];
}

/**
 * 生成翻页
 * @param string $url 页面地址
 * @param int $count 总数
 * @param int $start 开始
 * @param int $limit 条数
 * 
 * @return string 返回翻页信息
 */
function pager($url, $count, $start, $limit) {
	try {
		//url =  index.php?p={page};	
		$currentpage = $start / $limit + 1;
		$prevPage = $currentpage - 1;
		$nextPage = $currentpage + 1;
		$lastPage = ceil ( $count / $limit );
		if ($nextPage > $lastPage) {
			$nextPage = $lastPage;
		}
		if($nextPage == 0){
			$nextPage =1;
		}
		if ($prevPage == 0) {
			$prevPage = 1;
		}
		if($lastPage == 0){
			$lastPage = 1;
		}
        $str= str_replace("&p={page}","",$url);
		$turnPage = '';
		//第一页			
		$turnPage .= ' <a href="' . str_replace ( '{page}', '1', $url ) . '">首页</a>';
		//上一页
		$turnPage .= ' &nbsp<a href="' . str_replace ( '{page}', $prevPage, $url ) . '">上一页</a>';
		//当前页
		//$turnPage .= '&nbsp;当前第' . strval ( $currentpage ) . '页';
		//下一页
		$turnPage .= ' &nbsp<a href="' . str_replace ( '{page}', $nextPage, $url ) . '">下一页</a>';
		//最后页
		$turnPage .= ' &nbsp<a href="' . str_replace ( '{page}', $lastPage, $url ) . '">尾页</a>';
		$turnPage .= " &nbsp;".$limit."条/页";
		$turnPage .= " &nbsp;$currentpage/$lastPage &nbsp总记录数:$count";
		$turnPage .= '&nbsp;跳转至';
        $turnPage .= '<select name="sel" onchange="document.location.href=';
        $turnPage .="'";
        $turnPage .=$str."&p='+(this.value)";
        $turnPage .='" >';
        $pagecount = $count/$limit;
        for($p=1;$p<=ceil($pagecount);$p++){
        $turnPage .= '<option value="'.$p.'" ';
            if($currentpage==$p){ 
                $turnPage .= "selected";
            }
            $turnPage .='>第'.$p.'页</option>';
            
        }
        $turnPage .='</select>';
        return $turnPage;
	} catch ( Exception $e ) {
		return '分页错误';
	}
}

/*
自定义函数，检测数组中的空值
*/
function isnull($var)
{
	if($var == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}
/*
** 过滤一些脏词汇
** $words 脏词汇列表
** $replace 要替换成的词汇
** 返回替换完的词汇
*/
function replace_danger_word($content){
		$words=array('妈的','sb','我靠');
		$replace ='*';
		foreach($words as $key=>$word){
			$content=str_replace($word,$replace,$content);
		}
		return $content;
}

/*
** 过滤一些js字符
** $string 要传入的字符
** 返回替换完的词汇
*/
function stripscript($string){
		$pregfind=array("/<script.*>.*<\/script>/siU",'/on(mousewheel|mouseover|click|load|onload|submit|focus|blur)="[^"]*"/i');
		$pregreplace=array('','',);
		$string=preg_replace($pregfind,$pregreplace,$string);
		return $string;
	}


/*
	检查是否站外提交
	站外提交直接弹出提示并终止
*/
function fs_checkpost()
{
	$servername=$HTTP_SERVER_VARS['SERVER_NAME'];

	$sub_from=$HTTP_SERVER_VARS["HTTP_REFERER"];

	$sub_len=strlen($servername);

	$checkfrom=substr($sub_from,7,$sub_len);

	if ($checkfrom!=$servername)
	{
		exit('程序终止!<br />如果是正常操作显示此错误 , 请直接联系工作人员!');
	}
}

//记录用户操作
function fs_record_user_do($member_id,$str)
{
	global $db;
	$sql = "insert into 7sx_event (member_id,event,datetime) value (".$member_id.",'".$str."',".time().")";
	$db -> query($sql);
}

//分钟转换为小时	这里是直接输出	并没有返回值
function fs_format_to_hour($m)
{
	printf( "%d小时%d分钟 ",floor($m/60),floor($m)%60);
}

//get client ip
function fs_getIP()
{
	if (isset($_SERVER)) { 
	if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
	    $realip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
	}
    elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { 
	    $realip = $_SERVER['HTTP_CLIENT_IP']; 
	}
    else { 
	    $realip = $_SERVER['REMOTE_ADDR']; 
	} 
	} else { 
	    if (getenv("HTTP_X_FORWARDED_FOR")) { 
	        $realip = getenv( "HTTP_X_FORWARDED_FOR"); 
	    } elseif (getenv("HTTP_CLIENT_IP")) { 
	        $realip = getenv("HTTP_CLIENT_IP"); 
	    } else { 
	        $realip = getenv("REMOTE_ADDR"); 
	    } 
	} 
	return $realip; 
}

//注册时生成随机码
function random($length)
{
     $strChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
     $max = strlen($strChars) - 1;
     mt_srand((double)microtime() * 1000000);
         for($i = 0; $i < $length; $i++)
         {
             $strStartName .= $strChars[mt_rand(0, $max)];
         }
         return $strStartName;
}
//根据状态ID显示状态
function fs_get_state_view($i)
{
	switch ($i)
	{
		case 1:return '不显示';break;
		case 0:return '显示';break;
		default:return '未知';break;
	}
}
//根据状态ID显示课程分类
function fs_get_course_fenlei($i)
{
	switch ($i)
	{
		case 0:return '必修课';break;
		case 1:return '选修课';break;
		default:return '必修课';break;
	}
}
//根据ID显示课件分类
function fs_get_kejian_fenlei($i)
{
	switch ($i)
	{
		case 1:return '梁构件';break;
		case 2:return '柱构件';break;
		case 3:return '墙构件';break;
		case 4:return '板构件';break;
		case 5:return '楼梯构件';break;
		case 6:return '基础构件';break;
		default:return ' ';break;
	}
}
//根据ID查询信息
function fs_get_objinfo($table,$field_id,$id,$field){
	global $db;
	$sql = "select ".$field." from ".$table." where ".$field_id." = ".$id;
	$result = $db -> query($sql);
	$row = $db -> fetch_array($result);
	return $row[$field];
}
//根据字段查询数量
function fs_get_objnum ($table,$field,$c){
	global $db;
	$sql = "select * from ".$table." where ".$field." = ".$c;
	$result = $db -> query($sql);
	$num = $db -> num_rows($result);
	return $num;
}
//用户是否第一次查看
function fs_first_view ($member_id,$field,$id){
	global $db;
	$sql = "select * from ".TABLE_LOOKCOST." where member_id = ".$member_id." and ".$field." = ".$id;
	$result = $db -> query($sql);
	$num = $db -> num_rows($result);
	if($num == 0){
        return true;
	}
	else{
		return false;
	}
}
//用户查看扣费
function fs_lookcosting ($table,$member_id,$field,$id,$datetime,$betime){
	global $db;
	$sql = "select * from ".TABLE_LOOKCOST." where member_id = ".$member_id." and ".$field." = ".$id;
	$result = $db -> query($sql);
	$row = $db -> fetch_array($result);
	$ditime = time() - $row['datetime'];
	if($betime < $ditime){
		//判断用户是否有足够的金币来查看
		if(fs_get_objinfo($table,$id,"costto") > fs_get_objinfo(TABLE_MEMBER,$member_id,"money")){
			fs_showmsg("您的余额不足，请充值后再查看！",DIR_ROOT_A."payed/");
		}
		else{
			$sql = "update ".TABLE_MEMBER." set money = money - ".fs_get_objinfo($table,$id,"costto")." where id = ".$member_id;
			$db -> query($sql);
			if(fs_first_view($member_id,$field,$id)){
				//第一次查看的话，插入数据库
				$db -> query("insert into ".TABLE_LOOKCOST." (member_id,".$field.",datetime) value (".$member_id.",".$id.",".$datetime.")");
			}
			else{
				//更新上次查看的时间
				$db -> query("update ".TABLE_LOOKCOST." set datetime = ".$datetime." where member_id = ".$member_id." and ".$field." = ".$id);
			}
		}
	}
}

/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8  开始长度默认为 0
*/    
function fs_cut_str($string, $sublen, $start = 0, $code = 'UTF-8')  {
	if($code == 'UTF-8'){
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		preg_match_all($pa, $string, $t_string);
		if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
		return join('', array_slice($t_string[0], $start, $sublen));
		}
		else{
			$start = $start*2;
			$sublen = $sublen*2;
			$strlen = strlen($string);
			$tmpstr = '';
			for($i=0; $i< $strlen; $i++){
				if($i>=$start && $i< ($start+$sublen)){
					if(ord(substr($string, $i, 1))>129){
						$tmpstr.= substr($string, $i, 2);
					}
					else{
						$tmpstr.= substr($string, $i, 1);
					}
				}
				if(ord(substr($string, $i, 1))>129)
				    $i++;
			}
			if(strlen($tmpstr)< $strlen )
			    $tmpstr.= "...";
			return $tmpstr;
		}
}
//英文全角转半角
function make_semiangle($str)   
{   
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',   
                 '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',   
                 'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',   
                 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',   
                 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',   
                 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',   
                 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',   
                 'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',   
                 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',   
                 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',   
                 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',   
                 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',   
                 'ｙ' => 'y', 'ｚ' => 'z',   
                 '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',   
                 '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',   
                 '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',   
                 '》' => '>',   
                 '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',   
                 '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',   
                 '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',   
                 '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',   
                 '　' => ' ');   
 
    return strtr($str, $arr);   
}
//发送激活邮件
function send_mail($to_address,$to_name,$id,$code)
{
	global $email_charset;
	global $email_host;
	global $email_username;
    global $email_stmpauto;
	global $email_password;
	global $email_from;
	global $email_fromname;
	global $email_subject;
	global $email_body;
	global $email_altbody;
	//下载的文件必须放在该文件所在目录
    require("email/class.phpmailer.php");
    include('email/email.php');
    //建立邮件发送类
	$mail = new PHPMailer();
	// 你可以根据您的语言调整字符集
	$mail -> CharSet = $email_charset; 
    // 使用SMTP方式发送
    $mail -> IsSMTP();
    // 您的企业邮局域名
	$mail -> Host = $email_host;
    // 启用SMTP验证功能
	$mail -> SMTPAuth = $email_stmpauto;
    // 邮局用户名(请填写完整的email地址)
	$mail -> Username = $email_username; 
    // 邮局密码
	$mail -> Password = $email_password;
    //邮件发送者email地址
	$mail -> From = $email_from;
	$mail -> FromName = $email_fromname;
    //收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
	$mail -> AddAddress($to_address,$to_name);
	/*
　　//$mail->AddReplyTo("", "");
    // 添加附件
	//$mail -> AddAttachment("");
	*/
    //是否使用HTML格式
	$mail -> IsHTML(true);// set email format to HTML 
    //邮件标题
	$mail -> Subject = $email_subject;
    //邮件内容
	$mail -> Body = $email_body."<br /><a href='".DOMAIN_ROOT."registe.php?do=".fs_sha1('jihuo')."&id=".$id."&code=".$code."'>".DOMAIN_ROOT."registe.php?do=".fs_sha1('jihuo')."&id=".fs_sha1($id)."&code=".$code."</a>";
    //附加信息，可以省略
	$mail -> AltBody = $email_altbody;
	if(!$mail -> Send()){
		echo("邮件发送失败.");
		echo("错误原因：".$mail -> ErrorInfo);
                return false;
	}
	else{
		return true;
	}
}

//验证是否登陆
function checkislogin(){
	if ($_SESSION['memberinfo']=='') {
		exit("<script>if(confirm('您还没有登陆，请先登陆！点击确定将进行登陆。')){window.location.href='".DIR_ROOT_A."login.php?return_url=".$_SERVER["HTTP_REFERER"]."'}else{history.go(-1);}</script>");
		//fs_showmsg('您还没有登陆，请先登陆！' , DIR_ROOT_A.'login.php?return_url='.$_SERVER["HTTP_REFERER"]); 
	}
}


//毫秒时间
function fs_getmicrotime(){
	list($usec, $sec) = explode(" ",microtime());
	return ((float)$usec + (float)$sec);
}

//返回运行时间
//$begintime $endtime $mark小数位数(数字)
function fs_getruntime($begintime , $endtime , $mark)
{
	return round(($endtime-$begintime),$mark);
}

/*输出导航当前页样式*/
function fs_getNavigateStyle($name)
{
	$httphost = $_SERVER['PHP_SELF'];
	if(strpos($httphost,$name))
	{
		echo('ishere');
	}
}

//显示试卷的难度
function fs_showim($i){
	switch($i){
	case 1:    return   "★☆☆☆☆"		;break;
	case 2:    return   "★★☆☆☆"		;break;
	case 3:    return   "★★★☆☆"		;break;
	case 4:    return   "★★★★☆"        ;break;
	case 5:    return   "★★★★★"        ;break;
	}
}

/* 获取最近一次插入的id*/
 function insert_id(){
         return mysql_insert_id();
 }
 //返回试题信息
function get_test_info($test_id,$str){
	global $db;
	$sql = "select * from ".DBPREFIX."exam where exam_id = ".$test_id;
	$result = $db -> query($sql);
	$row = $db -> fetch_array($result);
	return $row[$str];
}
//截取中文字符串 qzr 2012-8-31
    function sub_str($str, $length)
{
    $str = trim($str);
    $strlength = strlen($str);

    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, 'utf-8');
    }
    elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, 'utf-8');
    }
    else
    {
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }

    if ( $str != $newstr)
    {
        $newstr .= '...';
    }
    return $newstr;
}
function get_count($table,$ziduan,$username)
{
    global $db;
    if($username==''){
        if($table!=''&&$_SESSION['sid']!=''&&$ziduan!='')
        {
            $query  = "select count(*) as num from ".DBPREFIX."$table where ".$ziduan."=".$_SESSION['sid'];
            $result = $db->query($query);
            $num =mysql_result($result,0);
            return $num;
        }
        else{
            return false;
        }
    }
    else{
        if($table!=''&&$_SESSION['sid']!=''&&$ziduan!='')
        {
            $query  = "select count(*) as num from ".DBPREFIX."$table where ".$ziduan."='".$_SESSION['username']."'";
            $result = $db->query($query);
            $num =mysql_result($result,0);
            return $num;
        }
        else{
            return false;
        }
    }
}
function get_record($type){//1:视频记录 2:文档下载记录 3:试卷查看记录
    global $db;
    $query = "select count(*) as num from ".DBPREFIX."record where uid=".$_SESSION['sid']." and type=".$type;
    $result = $db->query($query);
    $num =mysql_result($result,0);
    return $num;
}
function get_all_count($table)
{
        global $db;
        if($table!='')
        {
            $query  = "select count(*) as num from ".DBPREFIX.$table;
            $result = $db->query($query);
            $num =mysql_result($result,0);
            return $num;
        }
        else{
            return false;
        }
}
/*
 * 
 * 
 */
function getIdByRealname($name){
    global $db;
    $query = "select * from ".DBPREFIX."member where realname='".$name."'";
    $result = $db->query($query);
    $member_info  = $db->fetch_array($result);
    return $member_info['id'];
}

function get_realname_uid($uid){
    global $db;
    $query = "select * from ".DBPREFIX."member where id='".$uid."'";
    $result = $db->query($query);
    $member_info  = $db->fetch_array($result);
    return $member_info['realname'];
}

function get_exam_name($exam_id)
{
    global $db;
    $query = "select * from ".DBPREFIX."exam where exam_id='".$exam_id."'";
    $result = $db->query($query);
    $member_info  = $db->fetch_array($result);
    return $member_info['exam_name'];
}

/*根据type 获取该type的信息*/
function getInfoByType($type,$order)
{
    global $db;
    if($type!=''&&$order!='')
    {
        $query ="select * from ".DBPREFIX.$type." order by  ".$order." DESC limit 0,30";
        $result = $db->query($query);
    }
}

/*通过session id  获取用户的信息*/
function getMemberById($sid){
     global $db;
     if($sid!='')
     {
         $query = "select * from ".DBPREFIX.'member where id='.$sid;
         $result  = $db->query($query);
         $memberinfo  = $db->fetch_array($result);
         return $memberinfo;
     }
}
?>